import {defineStore} from 'pinia'
import {ref} from 'vue'
import to from 'await-to-js'
import {tip} from '@/utils/uni-api-wrap/toast'
import {isEmptyObj, isInvalidData, lockWrap} from '@/utils/utils'
import {reLaunch} from '@/utils/uni-api-wrap/route'
import {fetchUserinfo, fetchUserLogin} from '@/api/user'
import {login} from '@/utils/uni-api-wrap/sys'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const userinfo = ref({})

    // 登录
    const loginAction = async (data = {}) => {
      let err, code, result
      if (isEmptyObj(data)) {
        [err, { code }] = await to(login({ provider: 'weixin', onlyAuthorize: true }))
        if (err) {
          console.log('获取code失败', err)
          return tip('登录：获取code失败')
        }
      }
      let response
      [err, result] = await to(fetchUserLogin({ data: code || data }))
      if (isInvalidData(err)) {
        token.value = result.data.result;
        userinfo.value = result.data.user
      }
    }

    // 注销方法
    const LogoutAction = lockWrap(async (remote = true) => {
      // todo 将to 函数里面的内容替换成注销的方法
      try { remote && await to(Promise.resolve('success')) } catch (e) {}
      return new Promise(resolve => {
        setTimeout(() => {
          // todo 注销成功逻辑
          token.value = ''
          reLaunch('/pages/index/index')
          resolve()
        }, 1000)
      })
    })

    const getUserInfo = lockWrap(async () => {
      // todo 将to 函数里面的内容替换成获取用户信息的方法
      const [err, result] = await to(fetchUserinfo())
      if (err || result?.code !== 0) return
      userinfo.value = result.data
    })

    watch(token, (newToken) => {
      if (newToken) getUserInfo()
    })

    return { token, userinfo, loginAction, LogoutAction, getUserInfo }
  },
  {
    unistorage: true // 配合插件pinia-plugin-unistorage，将数据持久化到缓存中
  }
)
